<template>
  <div style="padding: 5px 15px 15px;margin-top: 12px;background-color: #fff;border-radius: 10px;">
    <search-filed :searchList="searchListArr" :selectField="searchFieldTmp" @clear="clearSearch" @close="closeOneField"/>
    <a-table size="middle" class="AcctTable" :rowKey="record=>record.id" style="margin-top: 12px" v-if="!expand"
      :columns="columns" :dataSource="data"
      :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
      :rowClassName="setRowClassName"
      :pagination="{onChange: changePage, ...pagination}" :loading="loading">
      <template slot="title" >
        <TableOperate ref="TableOperate" :valueFileds="valueFileds"
        :searchList="searchListArr" searchTitle="邮箱" :operateBtn="getBtn"
        @searchFormValue="searchFormValue" :noDate="true"  @batchOperation="(id)=> updateStatus(id, selectedRowKeys)"
        />
      </template>
      <template slot="name" slot-scope="text, record">
        <p class="updateText" :record="record">{{text}}</p>
      </template>
      <template slot="role" slot-scope="text, record">
        <p :record="record">{{text === 'ROLE_HRBP' ? '管理员' : (text === 'ROLE_ADMIN' ? '超级管理员' : '会员')}}</p>
      </template>
      <template slot="status" slot-scope="text">
        <a-icon :type="text === 'ENABLE'?'check-circle': 'close-circle'" :class="text === 'ENABLE'?'green':'grey'"/>
      </template>
      <template slot="action" slot-scope="text, record">
        <p class="update" v-if="!forbidControl">
          <a-button type="primary" size="small" @click="editAcct(record)">{{$t('common.compile')}}</a-button>
          <a-button :type="item.id === 'ENABLE'? 'primary' : 'danger'" size="small" v-for="item in filterBtn(operateBtn, record, recordBtn)" :key="item.id" :class="item.class" @click="() => updateStatus(item.id, [record.id])">{{$t(item.name)}}</a-button>
        </p>
      </template>
    </a-table>

    <a-table size="middle" class="AcctTable" :rowKey="record=>record.id" style="margin-top: 12px" v-else
      :columns="columns" :dataSource="data"
      :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, getCheckboxProps: getCheckboxProps}"
      :rowClassName="setRowClassName"
      :pagination="{onChange: changePage, ...pagination}" :loading="loading">
      <template slot="title" >
        <TableOperate ref="TableOperate" :valueFileds="valueFileds"
        :searchList="searchListArr" searchTitle="邮箱" :operateBtn="getBtn1"
        @searchFormValue="searchFormValue" :noDate="true"  @batchOperation="(id)=> updateStatus(id, selectedRowKeys)"
        />
      </template>
      <template slot="memberRole" slot-scope="text, record">
        <p :record="record">{{text === 'teacher' ? '授课会员' : '普通会员'}}</p>
      </template>
      <template slot="name" slot-scope="text, record">
        <p class="updateText" :record="record">{{text}}</p>
      </template>
      <template slot="gender" slot-scope="text, record">
        <p :record="record">{{text === 'male' ? '男' : '女'}}</p>
      </template>
      <template slot="subject" slot-scope="text, record">
        <p :record="record">{{getSubject(text)}}</p>
      </template>
      <!-- <template slot="status" slot-scope="text">
        <a-icon :type="text === 'ENABLE'?'check-circle': 'close-circle'" :class="text === 'ENABLE'?'green':'grey'"/>
      </template> -->
      <template slot="dateCreated" slot-scope="text, record">
        <p :record="record">{{moment(text).format('YYYY-MM-DD HH:mm:ss')}}</p>
      </template>
      <template slot="action" slot-scope="text, record">
        <p class="update flex" v-if="!forbidControl && fromPage === 'memberAudit'">
          <span v-if="record.auditsStatus === 'PASS'" class="info_text">已通过</span>
          <span v-if="record.auditsStatus === 'NOTPASS'" class="error_text">已拒绝</span>
          <span v-if="record.auditsStatus === 'WAIT'">待审核</span>
        </p>
      </template>
      <template slot="action1" slot-scope="text, record">
        <p class="update flex" v-if="!forbidControl && fromPage === 'memberAudit' && record.auditsStatus === 'WAIT'">
          <a-button type="primary" size="small" @click="updateAuditStatus('PASS', [record.id])" class="mr10">通过</a-button>
          <a-button type="danger" size="small" @click="rejectVisible = true;rejectIds = [record.id];">拒绝</a-button>
        </p>
        <p class="update flex" v-if="!forbidControl && fromPage === 'memberAudit' && record.auditsStatus === 'PASS'">
          <a-button type="primary" size="small" @click="() => updateStatus('ENABLE', [record.id])" v-if="record.status === 'DISABLE'" class="mr10">启用</a-button>
          <a-button type="danger" size="small" @click="() => updateStatus('DISABLE', [record.id])" v-if="record.status === 'ENABLE'">禁用</a-button>
        </p>
      </template>
      <template slot="expandedRowRender" slot-scope="record" style="margin: 0">
          <div class="ml20 expand_wrap" v-if="fromPage === 'memberAudit'">
            <div class="flex">
              <div class="mr20">学校名称：<span>{{ record.school }}</span></div>
              <div class="mr20">职称：<span>{{ record.proTitle }}</span></div>
              <div class="mr20">职务：<span>{{ record.job }}</span></div>
              <div class="mr20">业务专长：<span>{{ record.major }}</span></div>
            </div>
            <div>
              <div v-for="(child, childIndex) in record.childList" :key="childIndex">
                <div>选课子弟{{ childIndex + 1 }}</div>
                <div class="flex">
                  <div class="mr20">姓名：{{ child.name }}</div>
                  <div class="mr20">性别：{{ child.gender === 'male' ? '男' : '女' }}</div>
                  <div class="mr20">出生日期：{{ child.birth }}</div>
                  <div class="mr20">联系电话：{{ child.phone }}</div>
                </div>
              </div>
            </div>
          </div>
      </template>
    </a-table>
    <a-modal v-model="rejectVisible" title="拒绝原因" @ok="reject">
      <div><span class="error_text">*</span>请填写拒绝原因：</div>
      <a-textarea v-model="rejectReason" class="mt10 mb10"></a-textarea>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment'
import TableOperate from '@/components/SearchList/TableOperate'
import SearchFiled from '@/components/SearchList/SearchFiled'
import { changeStatusAccount, changeAuditStatus } from '@/api/config'
import { filterBtn, recordBtn } from '@/util/roles'
const columns = [
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    scopedSlots: { customRender: 'name' }
  },
  {
    title: '电话',
    dataIndex: 'phone',
    key: 'phone'
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email'
  },
  {
    title: '帐号类型',
    dataIndex: 'role',
    key: 'role',
    scopedSlots: { customRender: 'role' }
  },
  {
    title: '职位总数',
    dataIndex: 'positionCount',
    key: 'positionCount'
  },
  {
    title: '简历总数',
    dataIndex: 'applicationCount',
    key: 'applicationCount'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    scopedSlots: { customRender: 'action' }
  }
]
const operateBtn = [{
  name: 'common.disable',
  status: 'status',
  statusValN: ['DISABLE'],
  id: 'DISABLE',
  class: 'red'
}, {
  name: 'common.enable',
  status: 'status',
  statusValN: ['ENABLE'],
  id: 'ENABLE'
}]
const operateBtn1 = [{
  name: 'candidateApplication.pass',
  status: 'status',
  statusValN: ['PASS'],
  id: 'PASS'
}, {
  name: 'candidateApplication.reject',
  status: 'status',
  statusValN: ['NOTPASS'],
  id: 'NOTPASS',
  class: 'red'
}, {
  name: 'common.disable',
  status: 'status',
  statusValN: ['DISABLE'],
  id: 'DISABLE',
  class: 'red'
}, {
  name: 'common.enable',
  status: 'status',
  statusValN: ['ENABLE'],
  id: 'ENABLE'
}]
const searchListArrOri = [
  {
    id: 'name',
    type: 'input',
    name: '姓名'
  // }, {
  //   id: 'email',
  //   type: 'input',
  //   name: '邮箱'
  }, {
    id: 'phone',
    type: 'input',
    name: '电话'
  },
  {
    id: 'status',
    type: 'select',
    name: '状态',
    values: [{ id: 'ENABLE', name: '启用' }, { id: 'DISABLE', name: '禁用' }],
    role: ['ROLE_ADMIN', 'ROLE_HRBP']
  }
]

export default {
  name: 'AcctTable',
  components: { TableOperate, SearchFiled },
  props: ['data', 'pagination', 'loading', 'selectedRowKeys', 'forbidControl', 'overWriteColumns', 'expand', 'fromPage'],
  data () {
    return {
      moment,
      acctList: [],
      visible: false,
      filterBtn,
      recordBtn,
      columns: this.overWriteColumns || columns.filter(item => item.key !== 'company'),
      searchListArr: searchListArrOri,
      operateBtn,
      operateBtn1,
      from: '',
      deliverDate: '',
      searchField: {},
      searchFieldTmp: {},
      valueFileds: null,
      rejectVisible: false,
      rejectIds: [],
      rejectReason: ''
    }
  },
  created () {
  },
  computed: {
    getBtn () {
      return this.selectedRowKeys.length > 0 && !this.forbidControl ? this.filterBtn(operateBtn, this.acctList, this.recordBtn) : null
    },
    getBtn1 () {
      let isAllPending = true
      let isAllPass = true
      let arr = []
      if (this.selectedRowKeys.length > 0 && !this.forbidControl) {
        arr = this.data.filter(t => this.selectedRowKeys.includes(t.id))
        arr.forEach(t => {
          if (t.auditsStatus !== 'WAIT') {
            isAllPending = false
          }
          if (t.auditsStatus !== 'PASS') {
            isAllPass = false
          }
        })
      }
      if (this.selectedRowKeys.length > 0 && !this.forbidControl && (this.$store.state.user.userInfo.role === 'ROLE_ADMIN' || this.$store.state.user.userInfo.role === 'ROLE_HRBP')) {
        if (isAllPending) {
          return this.operateBtn1.slice(0, 2)
        }
        if (isAllPass) {
          if (arr[0].status === 'ENABLE') {
            return this.operateBtn1.slice(2, 3)
          } else {
            return this.operateBtn1.slice(3, 4)
          }
        }
      }
      return null
    }
  },
  watch: {
    '$route.query.auditsStatus': {
      handler (newValue, oldValue) {
        // 会员审核列表里 只有全部和通过需要显示状态禁用启用查询
        this.searchListArr = searchListArrOri.filter(item => ['WAIT', 'NOTPASS'].includes(newValue) ? item.id !== 'status' : true)
      },
      immediate: true
    }
  },
  methods: {
    closeOneField (id) {
      // if (!this.valueFileds) {
      this.valueFileds = {}
      // }
      this.$set(this.valueFileds, id, '')
    },
    onSelectChange (selectedRowKeys, acctList) {
      this.acctList = acctList
      this.$emit('setSelected', selectedRowKeys)
      // this.selectedRowKeys = selectedRowKeys
    },
    clearSearch () {
      this.$refs.TableOperate.clearSearch()
    },
    // 管理员账号 和 会员账号 的启用和禁用
    async updateStatus (status, ids) {
      if (status === 'PASS' || status === 'NOTPASS') {
        this.updateAuditStatus(status, ids)
        return false
      }
      let prams = ids.map(id => {
        return { status, id }
      })
      console.info(prams)
      let res = await changeStatusAccount(prams)
      if (res.code === 200) {
        this.$message.success(res.message)
        let pagination = this.pagination
        pagination.current = 1
        this.$emit('update', { searchField: this.searchFieldTmp, pagination })
      } else {
        this.$message.error(res.message)
      }
    },
    // 会员账号批量审核通过或拒绝
    updateAuditStatus (status, ids) {
      let prams = null
      if (status === 'PASS') { // 会员账号审核通过
        prams = ids.map(id => {
          return { status, id }
        })
        console.info(prams)
        this.$confirm({
          title: '是否确定通过审核？',
          onOk: async () => {
            let res = await changeAuditStatus(prams)
            if (res.code === 200) {
              this.$message.success('操作成功')
              let pagination = this.pagination
              pagination.current = 1
              this.$emit('update', { searchField: this.searchFieldTmp, pagination })
            } else {
              this.$message.error(res.message)
            }
          },
          onCancel () {
          },
          class: 'test'
        })
      } else { // 会员账号审核拒绝
        this.rejectIds = ids
        this.rejectVisible = true
      }
    },
    // 会员账号审核拒绝
    async reject () {
      console.info(this.rejectReason)
      if (!this.rejectReason) {
        this.$message.error('请填写拒绝原因')
        return false
      }
      let prams = this.rejectIds.map(id => {
        return { status: 'NOTPASS', id, reason: this.rejectReason }
      })
      console.info(prams)
      let res = await changeAuditStatus(prams)
      if (res.code === 200) {
        this.$message.success('操作成功')
        let pagination = this.pagination
        pagination.current = 1
        this.$emit('update', { searchField: this.searchFieldTmp, pagination })
      } else {
        this.$message.error(res.message)
      }
      this.rejectVisible = false
    },
    searchFormValue (searchField) {
      this.searchFieldTmp = searchField
      let searchFieldTmp = JSON.parse(JSON.stringify(searchField))
      this.searchField = searchFieldTmp
      searchFieldTmp.key = searchFieldTmp.keyword
      delete searchFieldTmp.keyword
      let pagination = this.pagination
      pagination.current = 1
      this.$emit('update', { searchField: searchFieldTmp, pagination })
    },
    editAcct (record) {
      this.$emit('addAcct', record)
    },
    changePage (current, pageSize) {
      let pagination = this.pagination
      pagination.current = current
      this.$emit('update', { searchField: this.searchField, pagination })
    },
    setRowClassName (record, index) {
      return index % 2 !== 0 ? 'grey' : ''
    },
    getCheckboxProps (record) {
      return {
        props: {
          disabled: record.auditsStatus === 'NOTPASS'
        }
      }
    },
    getSubject (subject) {
      let options = [
        { value: 'science', label: '科学(对应理、工和医学部)' },
        { value: 'humanity', label: '人文(对应人文社科学部)' },
        { value: 'foreignLanguage', label: '外语(对应外国语学院)' },
        { value: 'art', label: '艺术(对应艺术学院)' },
        { value: 'sports', label: '体育(对应体育教研部)' }
      ]
      let str = []
      subject && subject.split(',').forEach(t => {
        options.forEach(o => {
          if (o.value === t) {
            str.push(o.label.slice(0, 2))
          }
        })
      })
      return str.join()
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '../../styles/var.styl'
.AcctTable
  :global(.top)
    padding 14px 18px!important
  background #fff
  .errorColor
    color errorColor
  .grey
    color textGrey
  .green
    color lightGreen
  // 表格头部公共写法
  // :global(.ant-table-title)
  //   padding 0
  // :global(.ant-table-thead th)
  //   background none
  //   padding 0
  // :global(.ant-table-thead .ant-table-header-column)
  //   display inline-block
  //   width calc(100% - 16px)
  //   padding 5px 8px
  //   margin 5px 8px
  //   border-right 1px solid borderColor
  // :global(.ant-table-thead th:first-child .ant-table-header-column)
  // :global(.ant-table-thead th:last-child .ant-table-header-column)
  //   border-right none
  // :global(.ant-table-tbody >tr >td)
  //   padding 7px 16px
  //   vertical-align top
  :global(.grey)
    background var(--light-grey)
  .updateText
    margin 0
    font-weight 600
  .update
    // visibility hidden
    margin 6px 0 0
    span
      // display none
      // display inline-block
      cursor pointer
      // border-right 1px solid borderColor
      padding 0
      color var(--blue-500)
      &.red
        color errorColor
      &:first-child
        padding-left 0
      &:last-child:after
        height 0
        // color errorColor
      &:after
        content ''
        vertical-align middle
        background borderColor
        display inline-block
        height 14px
        width 1px
        margin-left 4px
  // :global(.ant-table-row)
  //   margin 0 12px
  // :global(.ant-table-row:hover)
  //   :global(td)
  //   .update
  //     >span
  //       display inline-block
      // visibility visible
.ant-table.ant-table-bordered .ant-table-title
  border none
::v-deep .ant-table-row
  border-bottom 1px solid borderColor
.expand_wrap
  font-size 12px
</style>
